//
//  BLInventoryViewController.m
//  blanket
//
//  Created by Mac on 2018/3/2.
//  Copyright © 2018年 stoneobs@icloud.com. All rights reserved.
//

#import "BLInventoryViewController.h"
#import "BLQingdanTableViewCell.h"
#import "STAddressModel.h"
#import "STAddressMangeController.h"
@interface BLInventoryViewController ()
@property(nonatomic, strong) STLabel                      *moneyLable;//金额
@property(nonatomic, strong) STButton                     *cofrimButton;//购买
@property(nonatomic, strong) STLabel                     *addLable;//默认地址
@property(nonatomic, strong) STAddressModel                     *addModel;
@end

@implementation BLInventoryViewController
- (void)setAddModel:(STAddressModel *)addModel{
    _addModel = addModel;
    self.addLable.text = [NSString stringWithFormat:@"%@    %@\n%@",
                          addModel.username,
                          addModel.mobile,
                          addModel.address
                          ];
}

#pragma mark --vc 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"清单";
    [self configSubView];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self sendFetchDefultAddRequuest];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --subView
- (void)configSubView{
    [self configBootomeView];
    [self configTableHeader];
}
- (void)configBootomeView{
    UIView  * bootomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth,[TMUtils tabbar].height)];
    bootomView.top = [TMUtils tabbar].top;
    bootomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bootomView];
    [bootomView st_showTopShadow];
    [bootomView st_showBottomLine];

   __weak typeof(self) weakSelf =  self;
    self.cofrimButton = [[STButton alloc] initWithFrame:CGRectMake(0, 7, 80, 35)
                                                  title:@"立即取件"
                                             titleColor:[UIColor whiteColor]
                                              titleFont:15
                                           cornerRadius:8
                                        backgroundColor:KL_BlueBackGroundColor
                                        backgroundImage:nil
                                                  image:nil];
    self.cofrimButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.cofrimButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedConfimButton];
    }];
    self.cofrimButton.right = UIScreenWidth - 10;
    [bootomView addSubview:self.cofrimButton];
    
    self.moneyLable = [[STLabel alloc] initWithFrame:CGRectMake( 10, 0, self.cofrimButton.left  - 20, 49)
                                                text:@"合计:$0"
                                           textColor:KL_redColor
                                                font:13
                                         isSizetoFit:NO
                                       textAlignment:NSTextAlignmentRight];
    self.moneyLable.attributedText = [self.moneyLable.text st_convertAttributeStringWithKeyWord:@"合计:"
                                                                                    attributes:@{NSForegroundColorAttributeName:KL_firstTextColor}];
    CGFloat money = 0;
    for (BLWashModel * model in self.dataSouce) {
        if (model) {
            money = money + model.price.floatValue * model.num.integerValue;
        }
    }
    self.moneyLable.text = [NSString stringWithFormat:@"合计:%0.2f",money];
    self.moneyLable.attributedText = [self.moneyLable.text st_convertAttributeStringWithKeyWord:@"合计:" attributes:@{NSForegroundColorAttributeName:KL_firstTextColor}];
    
    [bootomView addSubview:self.moneyLable];
    
}
- (void)configTableHeader{
    UIView * tableHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 40)];
    tableHeader.backgroundColor = [UIColor whiteColor];
    
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(15, 0, UIScreenWidth, 40)
                                                     text:@"收货地址"
                                                textColor:BL_firstTextColor
                                                     font:14
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [tableHeader addSubview:titleLable];
    
    UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(0, titleLable.bottom, UIScreenWidth, 1)];
    lineView.backgroundColor = BL_lineColor;
    [tableHeader addSubview:lineView];
    
    self.addLable = [[STLabel alloc] initWithFrame:CGRectMake(15, lineView.bottom, UIScreenWidth - 15 - 60, 80)
                                                     text:@"请绑定默认收货地址"
                                                textColor:BL_firstTextColor
                                                     font:14
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [tableHeader addSubview:self.addLable];
    UITapGestureRecognizer * tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapAddLable)];
    self.addLable.userInteractionEnabled = YES;
    [self.addLable addGestureRecognizer:tapGes];
    
    STButton * buyButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)
                                                     title:nil
                                                titleColor:nil
                                                 titleFont:0
                                              cornerRadius:0
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:[UIImage imageNamed:@"查看订单"]];
    buyButton.centerY = self.addLable.centerY;
    buyButton.right = UIScreenWidth - 15;
    buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [tableHeader addSubview:buyButton];
    
    UIView * footeView = [[UIView alloc] initWithFrame:CGRectMake(0, self.addLable.bottom, UIScreenWidth, 10)];
    footeView.backgroundColor = self.tableView.backgroundColor;
    [tableHeader addSubview:footeView];
    
    NSArray * array = @[@"名称",@"类别",@"属性",@"数量",@"单价",@"备注"];
    CGFloat with = UIScreenWidth / array.count;
    CGFloat left = 0;
    for (int i = 0; i < array.count; i ++) {
        NSString * title = array[i];
        STLabel * menuLable = [[STLabel alloc] initWithFrame:CGRectMake(left, footeView.bottom, with, 32)
                                                         text:title
                                                    textColor:BL_secendTextColor
                                                         font:12
                                                  isSizetoFit:NO
                                                textAlignment:NSTextAlignmentCenter];
        [tableHeader addSubview:menuLable];
        left = menuLable.right;
        [menuLable st_showBottomLine];
        if (i != array.count - 1) {
            [menuLable st_showRightLine:menuLable.height];
        }
    }
    
    tableHeader.height = footeView.bottom  +32;
    self.tableView.tableHeaderView = tableHeader;
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count ;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [BLQingdanTableViewCell cellHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    BLQingdanTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[BLQingdanTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    cell.washModel = self.dataSouce[indexPath.row];
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark --Action Method
- (void)onSelectedConfimButton{
    if (!self.dataSouce.count) {
        return;
    }
    
    [self showAlertWithTitle:[NSString stringWithFormat:@"您将盖币 支付%@",self.moneyLable.text]
                  titleColor:KL_firstTextColor
                     message:@"确认支付吗？"
                messageColor:BL_redColor
                   leftTitle:@"取消"
              leftTitleColor:KL_firstTextColor
                  rightTitle:@"确认"
             rightTitleColor:BL_BlueBackGroundColor
                      handle:^(NSString *name) {
                          if ([name isEqualToString:@"确认"]) {
                              [self sendBuyRequest];
                          }
                      }];
    
}
- (void)onTapAddLable{
    STAddressMangeController  * vc = [STAddressMangeController new];
    vc.type = @"1";
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark --NetWork Method
- (void)sendFetchDefultAddRequuest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/userDefaultAddress"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 NSString * modelDic =  responseObject[@"data"];
                                                 self.addModel = [STAddressModel mj_objectWithKeyValues:modelDic];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendBuyRequest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/washGoodsBuy"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if (self.addModel.address.length) {
      [dic setObject:self.addModel.address forKey:@"address"];
    }
    if (self.addModel.mobile.length) {
        [dic setObject:self.addModel.mobile forKey:@"mobile"];
    }
    if (self.addModel.username.length) {
        [dic setObject:self.addModel.username forKey:@"username"];
    }
    //washjson
    NSMutableArray * array = [NSMutableArray new];
    for (BLWashModel * model in self.dataSouce) {
        NSDictionary * modelDic = @{@"gid":model.washID,
                               @"menu_id":model.goods_menu_id,
                               @"cate_id":model.cate_id,
                               @"num":model.num,
                               @"intro":@"",
                               @"money":model.price,
                               @"goods_name":model.name,
                               };
        [array addObject:modelDic];
    }
    NSString * jsonString = array.mj_JSONString;
    [dic setObject:jsonString forKey:@"wash_json"];
    
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"购买成功"];
                                                 [self.navigationController popToRootViewControllerAnimated:YES];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end
